/**
 * Created by sun on 2015/3/12.
 */
package com.jbm.jbmsupplier.util;
import com.google.protobuf.GeneratedMessage;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

public class OHEncoder extends ProtocolEncoderAdapter
{
    private final String charset;
    public OHEncoder(String charset) {
        this.charset = charset;
    }

    public void encode(IoSession session, Object message,
                       ProtocolEncoderOutput out) throws Exception {

        int protoc_type = Integer.parseInt ( ( String )session.getAttribute( "PROTOC_TYPE") );

        IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);

        if ( protoc_type == 0 )
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(message);
            byte[] bytes = baos.toByteArray();

            buf.putInt(bytes.length & 0x0FFFFFFF);
            buf.put(bytes);
            buf.flip();
        }else if ( protoc_type == 0x10 )
        {
            String cname = message.getClass().getSimpleName();

            int len = 2;

            byte[] bytes;
            byte[] bname = cname.getBytes("UTF8");

            len += bname.length;

            if ( cname.equals("String"))
                bytes = ((String)message).getBytes("UTF8");
            else
            {
                GeneratedMessage pb = ( GeneratedMessage )TransClass.ItoProtocolBuffer(message);
                bytes = pb.toByteArray();
            }

            len += bytes.length;

            len = ((len&0x0FFFFFFF)|(protoc_type<<24));
            buf.putInt(len);
            buf.putShort((short)cname.length());
            buf.put(bname);
            buf.put(bytes);
            buf.flip();
        }
        out.write(buf);
    }
}
